package com.wfcm.controller;

import com.wfcm.entity.CourseWork;
import com.wfcm.service.WfCourseWorkService;
import com.wfcm.utils.Constants;
import com.wfcm.utils.ISsoLoginHelper;
import com.wfcm.utils.OSSUtil;
import com.wfcm.utils.R;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("course/work")
public class CourseWorkController {

    private Logger logger = LoggerFactory.getLogger(CourseWorkController.class);

    @Autowired
    private WfCourseWorkService courseWorkService;

    @RequestMapping("myCourseWork")
    public R myCourseWork(HttpServletRequest req) {
        R r = R.ok();
        try {
            Integer userId = ISsoLoginHelper.confirm(req);
            List<CourseWork> list = courseWorkService.myCourseWork(userId);
            TreeSet<Integer> courseId = new TreeSet<>();
            TreeSet<Integer> chapterId = new TreeSet<>();
            list.stream().forEach(courseWork -> {
                if (courseWork != null) {
                    if (StringUtils.isNotBlank(courseWork.getCourseIds())) {
                        for (String s : courseWork.getCourseIds().split(",")) {
                            if (StringUtils.isNotBlank(s)) {
                                courseId.add(Integer.valueOf(s));
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(courseWork.getChapterIds())) {
                        for (String s : courseWork.getChapterIds().split(",")) {
                            if (StringUtils.isNotBlank(s)) {
                                chapterId.add(Integer.valueOf(s));
                            }
                        }
                    }
                }
            });
            r.put("courseCount", courseId.size());
            r.put("chapterCount", chapterId.size());
            r.put("finishedCount", courseWorkService.finishedCourseWork(userId));
            if (chapterId.size() > 0) {
                List<CourseWork> myCourseWorkList = courseWorkService.myCourseWorkList(new CourseWork(userId, StringUtils.join(chapterId, ",")));
                List<CourseWork> result = new ArrayList<>();
                Map<String, List<CourseWork>> map = myCourseWorkList.stream().collect(Collectors.groupingBy(CourseWork::getCourseName));
                map.forEach((key, value) -> {
                    List<CourseWork> chapters = value.stream().sorted(Comparator.comparing(CourseWork::getSort)).collect(Collectors.toList());
                    result.add(new CourseWork(key, chapters));
                });
                r.put("result", result);
            }
        } catch (Exception e) {
            r = R.error(500, "服务器异常！");
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @RequestMapping("doHomework")
    public R doHomework(@RequestBody CourseWork cw, HttpServletRequest req) {
        R r = R.ok();
        try {
            Integer userId = ISsoLoginHelper.confirm(req);
            cw.setUserId(userId);
            CourseWork courseWork = courseWorkService.queryMemberWork(cw);
            if (courseWork != null) {
                r.put("courseWork", courseWork);
            } else {
                r.put("courseWork", courseWorkService.queryCourseWorkByChapterId(cw));
            }
        } catch (Exception e) {
            r = R.error(500, "服务器异常！");
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @RequestMapping("insertHomework")
    public R insertHomework(@RequestBody CourseWork courseWork, HttpServletRequest req) {
        R r = R.ok();
        try {
            Integer userId = ISsoLoginHelper.confirm(req);
            courseWork.setUserId(userId);
            CourseWork cw = courseWorkService.queryMemberWork(courseWork);
            if (cw != null) {
                courseWorkService.updateMemberWork(courseWork);
            } else {
                courseWorkService.insertMemberWork(courseWork);
            }
        } catch (Exception e) {
            r = R.error(500, "服务器异常！");
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @RequestMapping("upload")
    public R upload(MultipartFile file, String base64File) {
        R r = R.ok();
        try {
            r.put("url", "");
            if (StringUtils.isNotBlank(base64File)) {
                byte[] buffer = new Base64().decode(base64File);
                InputStream stream = new ByteArrayInputStream(buffer);
                r.put("url", OSSUtil.putFile(stream, "homework", Constants.IGM_BUCKET));
            } else if (null != file && !file.isEmpty()) {
                r.put("url", OSSUtil.addFile(file, "homework", Constants.IGM_BUCKET));
            }
        } catch (Exception e) {
            r = R.error(500, "服务器异常！");
            logger.error(e.getMessage(), e);
        }
        return r;
    }
}
